package com.dews.information.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dews.common.core.domain.model.LoginUser;
import com.dews.common.exception.ServiceException;
import com.dews.common.utils.SecurityUtils;
import com.dews.information.convert.StudentInfoConvert;
import com.dews.information.domain.dto.StudentInfoDTO;
import com.dews.information.domain.dto.StudentInfoQueryDTO;
import com.dews.information.domain.entity.ClazzInfo;
import com.dews.information.domain.entity.StudentInfo;
import com.dews.information.domain.entity.Subject;
import com.dews.information.domain.vo.StudentInfoVo;
import com.dews.information.mapper.ClazzInfoMapper;
import com.dews.information.mapper.StudentInfoMapper;
import com.dews.information.mapper.SubjectMapper;
import com.dews.information.service.IStudentInfoService;
import com.dews.system.domain.SysDept;
import com.dews.system.domain.SysUser;
import com.dews.system.domain.SysUserRole;
import com.dews.system.mapper.SysDeptMapper;
import com.dews.system.mapper.SysUserMapper;
import com.dews.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生信息详情Service业务层处理
 *
 * @author qingfeng
 * @date 2025-01-14
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements IStudentInfoService {

    private StudentInfoMapper studentInfoMapper;
    private SysDeptMapper sysDeptMapper;
    private SubjectMapper subjectMapper;
    private ClazzInfoMapper clazzInfoMapper;
    private SysUserMapper sysUserMapper;
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    public StudentInfoServiceImpl(StudentInfoMapper studentInfoMapper,
                                  SysDeptMapper sysDeptMapper,
                                  SubjectMapper subjectMapper,
                                  ClazzInfoMapper clazzInfoMapper,
                                  SysUserMapper sysUserMapper,
                                  SysUserRoleMapper sysUserRoleMapper) {
        this.studentInfoMapper = studentInfoMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.subjectMapper = subjectMapper;
        this.clazzInfoMapper = clazzInfoMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
    }

    /**
     * 查询学生信息详情列表
     *
     * @param studentInfoQueryDTO
     * @return 学生信息详情
     */
    @Override
    public List<StudentInfoVo> selectStudentInfoList(StudentInfoQueryDTO studentInfoQueryDTO) {
        List<StudentInfo> studentInfoList = baseMapper.selectList(
                new LambdaQueryWrapper<StudentInfo>()
                        .eq(ObjectUtil.isNotNull(studentInfoQueryDTO.getDepId()), StudentInfo::getDepId, studentInfoQueryDTO.getDepId())
                        .eq(ObjectUtil.isNotNull(studentInfoQueryDTO.getSubjectId()), StudentInfo::getSubjectId, studentInfoQueryDTO.getSubjectId())
                        .eq(ObjectUtil.isNotNull(studentInfoQueryDTO.getClazzId()), StudentInfo::getClazzId, studentInfoQueryDTO.getClazzId())
                        .like(StrUtil.isNotBlank(studentInfoQueryDTO.getStudentName()), StudentInfo::getStudentName, studentInfoQueryDTO.getStudentName())
                        .eq(StrUtil.isNotBlank(studentInfoQueryDTO.getNation()), StudentInfo::getNation, studentInfoQueryDTO.getNation())
                        .eq(StrUtil.isNotBlank(studentInfoQueryDTO.getPoliticsStatus()), StudentInfo::getPoliticsStatus, studentInfoQueryDTO.getPoliticsStatus())
                        .like(StrUtil.isNotBlank(studentInfoQueryDTO.getIdCard()), StudentInfo::getIdCard, studentInfoQueryDTO.getIdCard())
                        .eq(StrUtil.isNotBlank(studentInfoQueryDTO.getStateSchool()), StudentInfo::getStateSchool, studentInfoQueryDTO.getStateSchool())
                        .like(StrUtil.isNotBlank(studentInfoQueryDTO.getGrade()), StudentInfo::getGrade, studentInfoQueryDTO.getGrade())
                        .eq(ObjectUtil.isNotNull(studentInfoQueryDTO.getEducationalSystem()), StudentInfo::getEducationalSystem, studentInfoQueryDTO.getEducationalSystem())
        );
        if (CollUtil.isEmpty(studentInfoList)) {
            return Collections.emptyList();
        }
        Map<Long, String> depMap = sysDeptMapper.selectList(
                        new LambdaQueryWrapper<SysDept>()
                                .in(SysDept::getDeptId, studentInfoList.stream().map(StudentInfo::getDepId).collect(Collectors.toSet()))
                ).stream()
                .collect(Collectors.toMap(
                        SysDept::getDeptId,
                        SysDept::getDeptName,
                        (oldVal, newVal) -> oldVal
                ));
        Map<Integer, String> subjectMap = subjectMapper.selectList(
                        new LambdaQueryWrapper<Subject>()
                                .in(Subject::getId, studentInfoList.stream().map(StudentInfo::getSubjectId).collect(Collectors.toSet()))
                ).stream()
                .collect(Collectors.toMap(
                        Subject::getId,
                        Subject::getSubjectName,
                        (oldVal, newVal) -> oldVal
                ));
        Map<Integer, String> clazzMap = clazzInfoMapper.selectList(
                        new LambdaQueryWrapper<ClazzInfo>()
                                .in(ClazzInfo::getId, studentInfoList.stream().map(StudentInfo::getClazzId).collect(Collectors.toSet()))
                ).stream()
                .collect(Collectors.toMap(
                        ClazzInfo::getId,
                        ClazzInfo::getClazzName,
                        (oldVal, newVal) -> oldVal
                ));
        List<StudentInfoVo> studentInfoVoList = StudentInfoConvert.INSTANCE.convert(studentInfoList);
        studentInfoVoList.forEach(e -> {
            e.setDepName(depMap.getOrDefault(e.getDepId(), ""));
            e.setSubjectName(subjectMap.getOrDefault(e.getSubjectId(), ""));
            e.setClazzName(clazzMap.getOrDefault(e.getClazzId(), ""));
        });
        return studentInfoVoList;
    }

    /**
     * 新增学生信息详情
     *
     * @param studentInfoDTO
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertStudentInfo(StudentInfoDTO studentInfoDTO) {
        // 确保身份证号是唯一的
        if (studentInfoMapper.selectCount(
                new LambdaQueryWrapper<StudentInfo>()
                        .eq(StudentInfo::getIdCard, studentInfoDTO.getIdCard())
        ) > 0) {
            throw new ServiceException("身份证号已经存在，请勿重复添加");
        }

        // 查询班级的信息
        ClazzInfo clazzInfo = clazzInfoMapper.selectById(studentInfoDTO.getClazzId());
        if (ObjectUtil.isEmpty(clazzInfo)) {
            throw new ServiceException("班级不存在！");
        }
        // 查询专业信息
        Subject subject = subjectMapper.selectById(clazzInfo.getSubjectId());
        if (ObjectUtil.isEmpty(subject)) {
            throw new ServiceException("专业不存在！");
        }
        // 新增的学生，学号要按规则生成，并查询是否已经存在账号  学号：年级+专业代码+班级代码+学号   String.format("%04d", studentInfoDTO.getId())
        String studentNum = clazzInfo.getGrade().replace("级", "") + subject.getSubjectCode() + clazzInfo.getClazzCode();
        // 查询已经存在的账号数量
        Integer count = sysUserMapper.selectAccountNum(studentNum);

        // 先创建账号
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(subject.getDepId());
        sysUser.setUserName(studentNum + String.format("%03d", count + 1));
        sysUser.setNickName(studentInfoDTO.getStudentName());
        // 取IdCard最后六位
        sysUser.setPassword(SecurityUtils.encryptPassword(studentInfoDTO.getIdCard().substring(studentInfoDTO.getIdCard().length() - 6)));
        sysUserMapper.insert(sysUser);

        // 分配用户角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(2L);
        sysUserRoleMapper.insert(sysUserRole);

        // 存储学生信息
        StudentInfo studentInfo = StudentInfoConvert.INSTANCE.convert(studentInfoDTO);
        studentInfo.setUserId(sysUser.getUserId());
        studentInfo.setDepId(subject.getDepId());
        studentInfo.setSubjectId(subject.getId());
        studentInfo.setStudentNum(studentNum + String.format("%03d", count + 1));
        return studentInfoMapper.insert(studentInfo);

    }

    /**
     * 修改学生信息详情
     *
     * @param studentInfoDTO
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStudentInfo(StudentInfoDTO studentInfoDTO) {
        if (studentInfoMapper.selectCount(
                new LambdaQueryWrapper<StudentInfo>()
                        .eq(StudentInfo::getStudentNum, studentInfoDTO.getStudentNum())
                        .ne(StudentInfo::getId, studentInfoDTO.getId())
        ) > 0) {
            throw new ServiceException("学号已经存在，请勿重复添加");
        }
        if (studentInfoMapper.selectCount(
                new LambdaQueryWrapper<StudentInfo>()
                        .eq(StudentInfo::getIdCard, studentInfoDTO.getIdCard())
                        .ne(StudentInfo::getId, studentInfoDTO.getId())
        ) > 0) {
            throw new ServiceException("身份证号已经存在，请勿重复添加");
        }
        SysUser sysUser = sysUserMapper.selectUserById(studentInfoDTO.getUserId());
        sysUser.setUserName(studentInfoDTO.getStudentNum());
        sysUser.setPassword(SecurityUtils.encryptPassword(studentInfoDTO.getIdCard().substring(studentInfoDTO.getIdCard().length() - 6)));
        sysUserMapper.updateById(sysUser);
        StudentInfo studentInfo = StudentInfoConvert.INSTANCE.convert(studentInfoDTO);
        return studentInfoMapper.updateById(studentInfo);
    }

    /**
     * 查询学生信息详情
     *
     * @param id 学生信息详情主键
     * @return 学生信息详情
     */
    @Override
    public StudentInfoVo selectStudentInfoById(Integer id) {
        StudentInfo studentInfo = studentInfoMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(studentInfo)) {
            StudentInfoVo studentInfoVo = StudentInfoConvert.INSTANCE.convert(studentInfo);
            // 获取学院名称
            studentInfoVo.setDepName(sysDeptMapper.selectById(studentInfoVo.getDepId()).getDeptName());
            // 获取专业名称
            studentInfoVo.setSubjectName(subjectMapper.selectById(studentInfoVo.getSubjectId()).getSubjectName());
            // 获取班级名称
            studentInfoVo.setClazzName(clazzInfoMapper.selectById(studentInfoVo.getClazzId()).getClazzName());
            return studentInfoVo;
        }
        return null;
    }

    /**
     * 批量删除学生信息详情
     *
     * @param ids 需要删除的学生信息详情主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteStudentInfoByIds(List<Integer> ids) {
        // 先删除账号
        ids.forEach(id -> {
            StudentInfo studentInfo = studentInfoMapper.selectById(id);
            SysUser sysUser = new SysUser();
            sysUser.setUserId(studentInfo.getUserId());
            sysUser.setDelFlag("2");
            sysUserMapper.updateUser(sysUser);
        });
        return studentInfoMapper.deleteBatchIds(ids);
    }

    /**
     * 查询学生的学籍信息
     * @return
     */
    @Override
    public StudentInfoVo getStudentGradeInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtil.isEmpty(loginUser)) {
            throw new ServiceException("当前用户不存在，不支持查询学籍信息！");
        }
        StudentInfo studentInfo = baseMapper.selectOne(new LambdaQueryWrapper<StudentInfo>().eq(StudentInfo::getUserId, loginUser.getUserId()));
        if (ObjectUtil.isEmpty(studentInfo)) {
            throw new ServiceException("学生用户不存在！");
        }
        SysDept sysDept = sysDeptMapper.selectById(studentInfo.getDepId());
        Subject subject = subjectMapper.selectById(studentInfo.getSubjectId());
        ClazzInfo clazzInfo = clazzInfoMapper.selectById(studentInfo.getClazzId());
        StudentInfoVo studentInfoVo = StudentInfoConvert.INSTANCE.convert(studentInfo);
        studentInfoVo.setDepName(ObjectUtil.isNotEmpty(sysDept) ? sysDept.getDeptName() : "");
        studentInfoVo.setSubjectName(ObjectUtil.isNotEmpty(subject) ? subject.getSubjectName() : "");
        studentInfoVo.setClazzName(ObjectUtil.isNotEmpty(clazzInfo) ? clazzInfo.getClazzName() : "");
        return studentInfoVo;
    }

}
